<template>
  <div class="homework-container">
    <h1 class="page-title">作业管理</h1>
    
    <div class="course-selection">
      <h2 class="section-title">选择课程</h2>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="course in courseList" :key="course.id">
          <el-card class="course-card" shadow="hover" @click="selectCourse(course)">
            <div class="course-icon" :style="{ background: course.color }">
              <el-icon :size="34">
                <component :is="course.icon" />
              </el-icon>
            </div>
            <div class="course-info">
              <h3>{{ course.name }}</h3>
              <p>{{ course.teacher }}</p>
              <div class="course-stats">
                <el-tag size="small" :type="getHomeworkStatusType(course.stats.pending)">
                  <el-icon><Clock /></el-icon>
                  待提交: {{ course.stats.pending }}
                </el-tag>
                <el-tag size="small" :type="getHomeworkStatusType(course.stats.submitted)">
                  <el-icon><Upload /></el-icon>
                  已提交: {{ course.stats.submitted }}
                </el-tag>
                <el-tag size="small" :type="getHomeworkStatusType(course.stats.graded)">
                  <el-icon><CircleCheck /></el-icon>
                  已批改: {{ course.stats.graded }}
                </el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <div v-if="selectedCourse" class="homework-list-section">
      <div class="section-header">
        <h2 class="section-title">{{ selectedCourse.name }} - 作业列表</h2>
        <el-button @click="backToCourseSelection">返回课程选择</el-button>
      </div>
      
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="全部作业" name="all">
          <el-table :data="filteredHomeworks" style="width: 100%" border>
            <el-table-column prop="title" label="作业标题" width="250" />
            <el-table-column prop="releaseTime" label="发布时间" width="180" />
            <el-table-column prop="deadline" label="截止时间" width="180" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  <el-icon v-if="scope.row.status === '未提交'"><Clock /></el-icon>
                  <el-icon v-else-if="scope.row.status === '已提交'"><Upload /></el-icon>
                  <el-icon v-else-if="scope.row.status === '已批改'"><CircleCheck /></el-icon>
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="score" label="成绩" width="100">
              <template #default="scope">
                <span v-if="scope.row.score !== null" :class="{ 'high-score': scope.row.score >= 90, 'low-score': scope.row.score < 60 }">
                  {{ scope.row.score }}
                </span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-space>
                  <el-button 
                    v-if="scope.row.status === '未提交'" 
                    type="primary" 
                    size="small"
                    @click="startHomework(scope.row)"
                  >
                    开始答题
                  </el-button>
                  <el-button 
                    v-else-if="scope.row.status === '已提交'" 
                    type="warning" 
                    size="small"
                    @click="modifyHomework(scope.row)"
                  >
                    修改作业
                  </el-button>
                  <el-button 
                    v-else-if="scope.row.status === '已批改'" 
                    type="success" 
                    size="small"
                    @click="viewGrade(scope.row)"
                  >
                    查看成绩
                  </el-button>
                  <el-button 
                    type="info" 
                    size="small"
                    @click="viewHomeworkDetails(scope.row)"
                  >
                    查看详情
                  </el-button>
                </el-space>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="待提交" name="pending">
          <el-empty v-if="pendingHomeworks.length === 0" description="暂无待提交作业" :image-size="120" />
          <el-table v-else :data="pendingHomeworks" style="width: 100%" border>
            <el-table-column prop="title" label="作业标题" width="250" />
            <el-table-column prop="releaseTime" label="发布时间" width="180" />
            <el-table-column prop="deadline" label="截止时间" width="180" />
            <el-table-column label="剩余时间" width="150">
              <template #default="scope">
                <el-tag 
                  :type="getRemainingTimeType(scope.row.remainingTime)" 
                  effect="dark"
                >
                  {{ scope.row.remainingTime }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="startHomework(scope.row)"
                >
                  开始答题
                </el-button>
                <el-button 
                  type="info" 
                  size="small"
                  @click="viewHomeworkDetails(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="已提交" name="submitted">
          <el-empty v-if="submittedHomeworks.length === 0" description="暂无已提交作业" :image-size="120" />
          <el-table v-else :data="submittedHomeworks" style="width: 100%" border>
            <el-table-column prop="title" label="作业标题" width="250" />
            <el-table-column prop="releaseTime" label="发布时间" width="180" />
            <el-table-column prop="submitTime" label="提交时间" width="180" />
            <el-table-column prop="status" label="状态" width="120">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button 
                  v-if="scope.row.status === '已提交'" 
                  type="warning" 
                  size="small"
                  @click="modifyHomework(scope.row)"
                >
                  修改作业
                </el-button>
                <el-button 
                  v-else-if="scope.row.status === '已批改'" 
                  type="success" 
                  size="small"
                  @click="viewGrade(scope.row)"
                >
                  查看成绩
                </el-button>
                <el-button 
                  type="info" 
                  size="small"
                  @click="viewHomeworkDetails(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="已批改" name="graded">
          <el-empty v-if="gradedHomeworks.length === 0" description="暂无已批改作业" :image-size="120" />
          <el-table v-else :data="gradedHomeworks" style="width: 100%" border>
            <el-table-column prop="title" label="作业标题" width="250" />
            <el-table-column prop="submitTime" label="提交时间" width="180" />
            <el-table-column prop="gradeTime" label="批改时间" width="180" />
            <el-table-column prop="score" label="成绩" width="100">
              <template #default="scope">
                <span :class="{ 'high-score': scope.row.score >= 90, 'low-score': scope.row.score < 60 }">
                  {{ scope.row.score }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button 
                  type="success" 
                  size="small"
                  @click="viewGrade(scope.row)"
                >
                  查看成绩
                </el-button>
                <el-button 
                  type="info" 
                  size="small"
                  @click="viewHomeworkDetails(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  Document, Reading, Edit, DataAnalysis, Notebook, 
  Collection, Promotion, Connection, Histogram,
  Clock, Upload, CircleCheck
} from '@element-plus/icons-vue'
import { studentApi } from '@/api'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 当前激活的标签页
const activeTab = ref('all')

// 课程列表
const courseList = ref([])

// 选中的课程
const selectedCourse = ref(null)

// 作业列表
const homeworkList = ref([])

// 初始化数据
onMounted(() => {
  fetchCourseList()
})

// 获取课程列表
const fetchCourseList = async () => {
  try {
    const res = await studentApi.getHomeworkCourses()
    if (res.code === 200 && res.data) {
      courseList.value = res.data
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('获取课程列表失败')
  }
}

// 获取作业列表
const fetchHomeworkList = async (courseId) => {
  try {
    const res = await studentApi.getHomeworkList({ courseId })
    if (res.code === 200 && res.data) {
      // 处理作业数据，计算剩余时间
      homeworkList.value = res.data.map(item => {
        return {
          ...item,
          remainingTime: calculateRemainingTime(item.deadline)
        }
      })
    }
  } catch (error) {
    console.error('获取作业列表失败:', error)
    ElMessage.error('获取作业列表失败')
  }
}

// 计算剩余时间
const calculateRemainingTime = (deadline) => {
  if (!deadline) return '未知'
  
  const now = new Date()
  const deadlineDate = new Date(deadline)
  
  if (now > deadlineDate) {
    return '已截止'
  }
  
  const diffTime = deadlineDate - now
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    // 计算剩余小时
    const diffHours = Math.ceil(diffTime / (1000 * 60 * 60))
    return `${diffHours}小时`
  }
  
  return `${diffDays}天`
}

// 筛选后的作业列表
const filteredHomeworks = computed(() => {
  return homeworkList.value
})

// 待提交的作业
const pendingHomeworks = computed(() => {
  return homeworkList.value.filter(item => item.status === '未提交')
})

// 已提交的作业
const submittedHomeworks = computed(() => {
  return homeworkList.value.filter(item => item.status === '已提交' || item.status === '已批改')
})

// 已批改的作业
const gradedHomeworks = computed(() => {
  return homeworkList.value.filter(item => item.status === '已批改')
})

// 获取作业状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case '未提交': return 'danger'
    case '已提交': return 'warning'
    case '已批改': return 'success'
    default: return 'info'
  }
}

// 获取剩余时间对应的类型
const getRemainingTimeType = (time) => {
  if (time === '已截止') return 'danger'
  if (time.includes('小时')) return 'warning'
  const days = parseInt(time)
  if (days <= 3) return 'warning'
  return 'info'
}

// 获取作业统计状态对应的类型
const getHomeworkStatusType = (count) => {
  if (count === 0) return 'info'
  return 'warning'
}

// 选择课程
const selectCourse = (course) => {
  selectedCourse.value = course
  activeTab.value = 'all'
  fetchHomeworkList(course.id)
}

// 返回课程选择
const backToCourseSelection = () => {
  selectedCourse.value = null
  homeworkList.value = []
}

// 开始作业
const startHomework = (homework) => {
  router.push({
    path: `/student/homework/detail`,
    query: {
      id: homework.id,
      mode: 'edit'
    }
  })
}

// 修改作业
const modifyHomework = (homework) => {
  router.push({
    path: `/student/homework/detail`,
    query: {
      id: homework.id,
      mode: 'edit'
    }
  })
}

// 查看成绩
const viewGrade = (homework) => {
  router.push({
    path: `/student/homework/detail`,
    query: {
      id: homework.id,
      mode: 'grade'
    }
  })
}

// 查看作业详情
const viewHomeworkDetails = (homework) => {
  router.push({
    path: `/student/homework/detail`,
    query: {
      id: homework.id,
      mode: 'view'
    }
  })
}
</script>

<style lang="scss" scoped>
.homework-container {
  padding: 20px;
  
  .page-title {
    margin-bottom: 20px;
    font-size: 24px;
    font-weight: bold;
    color: #303133;
  }
  
  .section-title {
    margin-bottom: 20px;
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }
  
  .course-selection {
    margin-bottom: 30px;
    
    .course-card {
      height: 200px;
      margin-bottom: 20px;
      cursor: pointer;
      border-radius: 18px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.08);
      transition: all 0.3s cubic-bezier(.25,.8,.25,1);
      background: #fff;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      &:hover {
        transform: translateY(-6px) scale(1.03);
        box-shadow: 0 6px 24px 0 rgba(0,0,0,0.13);
      }
      .course-icon {
        width: 64px;
        height: 64px;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 auto 15px;
        color: #fff;
        background: linear-gradient(135deg, #6dd5ed 0%, #2193b0 100%);
        box-shadow: 0 2px 8px 0 rgba(33,147,176,0.15);
        font-size: 32px;
        transition: background 0.3s;
      }
      .course-info {
        text-align: center;
        h3 {
          margin-bottom: 8px;
          font-size: 17px;
          font-weight: bold;
          color: #222;
        }
        p {
          margin-bottom: 12px;
          font-size: 13px;
          color: #888;
        }
        .course-stats {
          display: flex;
          justify-content: center;
          gap: 8px;
          .el-tag {
            display: flex;
            align-items: center;
            gap: 2px;
            font-size: 12px;
            border-radius: 8px;
            padding: 0 8px;
            .el-icon {
              margin-right: 2px;
            }
          }
        }
      }
    }
  }
  
  .homework-list-section {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }
    .el-tabs {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
      padding: 10px 0 0 0;
      .el-tabs__item.is-active {
        color: #2193b0;
        font-weight: bold;
        background: linear-gradient(90deg, #e0eafc 0%, #cfdef3 100%);
        border-radius: 8px 8px 0 0;
      }
    }
    .el-table {
      border-radius: 10px;
      overflow: hidden;
      font-size: 14px;
      .el-table__row:hover {
        background: #f4faff;
        transition: background 0.2s;
      }
      .el-tag {
        border-radius: 8px;
        font-size: 12px;
        .el-icon {
          margin-right: 2px;
        }
      }
      .high-score {
        color: #67C23A;
        font-weight: bold;
      }
      .low-score {
        color: #F56C6C;
        font-weight: bold;
      }
    }
    .el-space {
      gap: 6px;
    }
  }
}

// 响应式样式
@media screen and (max-width: 768px) {
  .homework-container {
    padding: 8px;
    .page-title {
      font-size: 18px;
    }
    .section-title {
      font-size: 15px;
    }
    .course-card {
      height: auto;
      .course-info {
        h3 {
          font-size: 14px;
        }
        p {
          font-size: 12px;
        }
        .course-stats {
          flex-direction: column;
          align-items: center;
          gap: 5px;
        }
      }
    }
    .el-table {
      font-size: 12px;
    }
    .el-button {
      font-size: 12px;
      padding: 6px 10px;
    }
  }
}
</style> 